package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/7/26 10:31
 * @Version 1.0
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    /**
     * 取消订单
     * @param orderId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void orderCancel(Long orderId, Message message, Channel channel){
        //  判断过程：orderInfo --- paymentInfo --- aliPay;
        //  判断
        try {
            if (null != orderId){
                //  判断当前订单的状态.
                OrderInfo orderInfo = orderService.getById(orderId);
                //  判断当前订单对象不为空，同时是未支付状态.
                if (null!=orderInfo && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  此时是否有交易记录：
                    PaymentInfo paymentInfo = this.paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    if (null != paymentInfo && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        //  判断是否有交易记录
                        Boolean exist = this.paymentFeignClient.checkPayment(orderId);
                        if (exist){
                            //  有交易记录 -- 说明用户扫码了 --> 调用关闭接口：如果关闭成功了，说明用户没有支付！
                            Boolean result = this.paymentFeignClient.closePay(orderId);
                            if (result){
                                //  说明关闭成功了.
                                //  可能需要关闭orderInfo + paymentInfo;
                                orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //  说明没有关闭成功,表示在即将过期的瞬间这个用户完成了支付操作.
                            }
                        }else {
                            //  没有交易记录 -- 说明根本没有扫码
                            //  可能需要关闭orderInfo + paymentInfo;
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    }else {
                        //  调用取消订单的方法. 需要关闭orderInfo
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  关闭订单消息.
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER_CLOSED,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER_CLOSED),
            key = {MqConst.ROUTING_ORDER_CLOSED}
    ))
    public void orderClosed(Long orderId ,Message message, Channel channel){
        try {
            //  判断
            if (null != orderId){
                //  利用业务字段防止消息重复消费
                OrderInfo orderInfo = this.orderService.getById(orderId);
                if (null!=orderInfo && !"CLOSED".equals(orderInfo.getOrderStatus())){
                    //  关闭订单。
                    this.orderService.updateOrderStatus(orderId, ProcessStatus.CLOSED);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //  手动签收
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听支付成功消息，修改订单状态.
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void paymentPay(Long orderId ,Message message ,Channel channel){
        try {
            //  判断
            if (null != orderId){
                OrderInfo orderInfo = this.orderService.getById(orderId);
                if (null != orderInfo && !"PAID".equals(orderInfo.getOrderStatus())){
                    //  修改订单状态.
                    this.orderService.updateOrderStatus(orderId,ProcessStatus.PAID);
                    //  这个地方发送消息给库存系统.
                    this.orderService.sendMsgToWare(orderId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  手动签收
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听减库存消息队列.
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void wareOrder(String wareJson,Message message, Channel channel){
        try {
            //  判断当前数据不为空
            if (!StringUtils.isEmpty(wareJson)){
                //  数据类型转换
                Map map = JSON.parseObject(wareJson, Map.class);
                //  获取到订单Id
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                //  判断减库存结果
                if ("DEDUCTED".equals(status)){
                    //  减库存成功.
                    this.orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
                }else {
                    //  减库存失败，超卖！ 订单-支付，但是库存缺不能发货！
                    //  记录日志或消息记录表. insert into exceptionMsg(orderId,msg) values (?,?);
                    //  远程调用其他仓库，看是否能够发货。如果能够发货并且发送成功之后，更新当前的订单状态. 保证数据最终一致性.
                    this.orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
